<template>
    <div class="wrapper">
        <!-- Header -->
        <header>
            <div class="header-left">
                <p>管理后台</p>
            </div>
            <div class="header-right">
                <span>{{ adminName }}</span>
                <button @click="logout">退出</button>
            </div>
        </header>

        <!-- 功能菜单 -->
        <div class="menu-section">
            <div 
                class="menu-item" 
                :class="{ active: currentTab === 'business' }"
                @click="switchTab('business')"
            >
                <i class="fa fa-store"></i>
                <span>商家管理</span>
            </div>
            <div 
                class="menu-item" 
                :class="{ active: currentTab === 'food' }"
                @click="switchTab('food')"
            >
                <i class="fa fa-cutlery"></i>
                <span>食品管理</span>
            </div>
        </div>

        <!-- 商家管理 -->
        <div v-if="currentTab === 'business'" class="content">
            <div class="section-title">
                <h3>商家管理</h3>
                <button class="add-btn" @click="showAddBusinessModal = true">
                    <i class="fa fa-plus"></i> 新增商家
                </button>
            </div>

            <div class="business-list">
                <div class="list-header">
                    <div class="col-id">ID</div>
                    <div class="col-name">商家名称</div>
                    <div class="col-explain">商家简介</div>
                    <div class="col-action">操作</div>
                </div>
                
                <div 
                    class="list-item" 
                    v-for="business in businessList" 
                    :key="business.businessId"
                >
                    <div class="col-id">{{ business.businessId }}</div>
                    <div class="col-name">{{ business.businessName }}</div>
                    <div class="col-explain">{{ business.businessExplain }}</div>
                    <div class="col-action">
                        <button class="edit-btn" @click="editBusiness(business)">
                            <i class="fa fa-edit"></i>
                        </button>
                        <button class="delete-btn" @click="deleteBusiness(business.businessId)">
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 食品管理 -->
        <div v-if="currentTab === 'food'" class="content">
            <div class="section-title">
                <h3>食品管理</h3>
                <div class="business-selector">
                    <select v-model="selectedBusinessId" @change="loadFoodList">
                        <option value="">请选择商家</option>
                        <option 
                            v-for="business in businessList" 
                            :key="business.businessId"
                            :value="business.businessId"
                        >
                            {{ business.businessName }}
                        </option>
                    </select>
                </div>
                <button 
                    class="add-btn" 
                    :disabled="!selectedBusinessId"
                    @click="showAddFoodModal = true"
                >
                    <i class="fa fa-plus"></i> 新增食品
                </button>
            </div>

            <div class="food-list" v-if="selectedBusinessId">
                <div class="list-header">
                    <div class="col-id">ID</div>
                    <div class="col-name">食品名称</div>
                    <div class="col-explain">食品简介</div>
                    <div class="col-price">价格</div>
                    <div class="col-action">操作</div>
                </div>
                
                <div 
                    class="list-item" 
                    v-for="food in foodList" 
                    :key="food.foodId"
                >
                    <div class="col-id">{{ food.foodId }}</div>
                    <div class="col-name">{{ food.foodName }}</div>
                    <div class="col-explain">{{ food.foodExplain }}</div>
                    <div class="col-price">¥{{ food.foodPrice }}</div>
                    <div class="col-action">
                        <button class="edit-btn" @click="editFood(food)">
                            <i class="fa fa-edit"></i>
                        </button>
                        <button class="delete-btn" @click="deleteFood(food.foodId)">
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>

            <div v-else class="empty-state">
                <p>请先选择商家查看食品列表</p>
            </div>
        </div>

        <!-- 新增/编辑商家模态框 -->
        <div class="modal-overlay" v-if="showAddBusinessModal || showEditBusinessModal" @click="closeBusinessModal">
            <div class="business-modal" @click.stop>
                <h3>{{ showAddBusinessModal ? '新增商家' : '编辑商家' }}</h3>
                
                <div class="form-group">
                    <label>商家名称：</label>
                    <input type="text" v-model="currentBusiness.businessName" placeholder="请输入商家名称" />
                </div>
                
                <div class="form-group">
                    <label>商家地址：</label>
                    <input type="text" v-model="currentBusiness.businessAddress" placeholder="请输入商家地址" />
                </div>
                
                <div class="form-group">
                    <label>商家简介：</label>
                    <input type="text" v-model="currentBusiness.businessExplain" placeholder="请输入商家简介" />
                </div>
                
                <div class="form-group">
                    <label>配送费用：</label>
                    <input type="number" v-model="currentBusiness.deliveryPrice" placeholder="请输入配送费用" />
                </div>
                
                <div class="modal-buttons">
                    <button class="cancel-btn" @click="closeBusinessModal">取消</button>
                    <button class="confirm-btn" @click="saveBusiness">
                        {{ showAddBusinessModal ? '新增' : '保存' }}
                    </button>
                </div>
            </div>
        </div>

        <!-- 新增/编辑食品模态框 -->
        <div class="modal-overlay" v-if="showAddFoodModal || showEditFoodModal" @click="closeFoodModal">
            <div class="business-modal" @click.stop>
                <h3>{{ showAddFoodModal ? '新增食品' : '编辑食品' }}</h3>
                
                <div class="form-group">
                    <label>食品名称：</label>
                    <input type="text" v-model="currentFood.foodName" placeholder="请输入食品名称" />
                </div>
                
                <div class="form-group">
                    <label>食品简介：</label>
                    <input type="text" v-model="currentFood.foodExplain" placeholder="请输入食品简介" />
                </div>
                
                <div class="form-group">
                    <label>食品价格：</label>
                    <input type="number" v-model="currentFood.foodPrice" placeholder="请输入食品价格" />
                </div>
                
                <div class="modal-buttons">
                    <button class="cancel-btn" @click="closeFoodModal">取消</button>
                    <button class="confirm-btn" @click="saveFood">
                        {{ showAddFoodModal ? '新增' : '保存' }}
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            adminName: '',
            currentTab: 'business',
            selectedBusinessId: '',
            
            // 模态框状态
            showAddBusinessModal: false,
            showEditBusinessModal: false,
            showAddFoodModal: false,
            showEditFoodModal: false,
            
            // 数据列表
            businessList: [],
            foodList: [],
            
            // 当前编辑项
            currentBusiness: {
                businessId: null,
                businessName: '',
                businessAddress: '',
                businessExplain: '',
                deliveryPrice: ''
            },
            currentFood: {
                foodId: null,
                foodName: '',
                foodExplain: '',
                foodPrice: '',
                businessId: ''
            }
        }
    },
    mounted() {
        this.checkAdminAuth()
        this.loadBusinessList()
    },
    methods: {
        // 检查管理员权限
        checkAdminAuth() {
            const adminInfo = this.$getSessionStorage('admin')
            if (!adminInfo) {
                alert('请先登录管理员账号')
                this.$router.push('/login')
                return
            }
            this.adminName = adminInfo.adminId || '管理员'  // 修正：使用 adminId
            console.log('管理员已登录:', adminInfo)
        },

        // 切换标签页
        switchTab(tab) {
            this.currentTab = tab
            if (tab === 'food') {
                this.selectedBusinessId = ''
                this.foodList = []
            }
        },

        // ========== 修改：加载商家列表 ==========
        async loadBusinessList() {
            try {
                console.log('=== 加载商家列表 ===')
                
                const response = await this.$axios.get('/business/listBusiness')
                
                console.log('商家列表响应:', response.data)
                
                if (response.data.code === 1) {
                    this.businessList = response.data.data || []
                    console.log('加载商家数量:', this.businessList.length)
                } else {
                    console.error('加载商家列表失败:', response.data.msg)
                    this.businessList = []
                }
                
            } catch (error) {
                console.error('加载商家列表错误:', error)
                this.businessList = []
            }
        },
        // ========== 商家列表加载修改结束 ==========

        // 加载食品列表
        async loadFoodList() {
            if (!this.selectedBusinessId) {
                this.foodList = []
                return
            }

            try {
                console.log('=== 加载食品列表 ===')
                console.log('商家ID:', this.selectedBusinessId)
                
                const response = await this.$axios.get(`/food/listFoodByBusinessId?businessId=${this.selectedBusinessId}`)
                
                console.log('食品列表响应:', response.data)
                
                if (response.data.code === 1) {
                    this.foodList = response.data.data || []
                    console.log('加载食品数量:', this.foodList.length)
                } else {
                    console.error('加载食品列表失败:', response.data.msg)
                    this.foodList = []
                }
                
            } catch (error) {
                console.error('加载食品列表错误:', error)
                this.foodList = []
            }
        },

        // 编辑商家
        editBusiness(business) {
            console.log('编辑商家:', business)
            this.currentBusiness = { ...business }
            this.showEditBusinessModal = true
        },

        // ========== 修改：删除商家 ==========
        async deleteBusiness(businessId) {
            if (!confirm('确定要删除这个商家吗？')) {
                return
            }

            try {
                console.log('删除商家:', businessId)
                
                const response = await this.$axios.post('/business/deleteBusiness', this.$qs.stringify({
                    businessId: businessId
                }))
                
                if (response.data.code === 1) {
                    alert('删除成功！')
                    this.loadBusinessList()
                } else {
                    alert(response.data.msg || '删除失败')
                }
                
            } catch (error) {
                console.error('删除错误:', error)
                alert('删除失败，请稍后重试')
            }
        },
        // ========== 删除商家修改结束 ==========

        // ========== 修改：保存商家 ==========
        async saveBusiness() {
            if (!this.currentBusiness.businessName.trim()) {
                alert('请输入商家名称')
                return
            }

            try {
                const isEdit = this.showEditBusinessModal
                console.log(isEdit ? '编辑商家:' : '新增商家:', this.currentBusiness)
                
                let endpoint
                let params = {
                    businessName: this.currentBusiness.businessName,
                    businessAddress: this.currentBusiness.businessAddress,
                    businessExplain: this.currentBusiness.businessExplain,
                    deliveryPrice: this.currentBusiness.deliveryPrice
                }
                
                if (isEdit) {
                    endpoint = '/business/updateBusiness'
                    params.businessId = this.currentBusiness.businessId
                } else {
                    endpoint = '/business/addBusiness'
                    // 新增时需要生成ID或由后端处理
                    params.businessId = Date.now() % 100000  // 简单生成ID
                }
                
                const response = await this.$axios.post(endpoint, this.$qs.stringify(params))
                
                if (response.data.code === 1) {
                    alert(isEdit ? '编辑成功！' : '新增成功！')
                    this.closeBusinessModal()
                    this.loadBusinessList()
                } else {
                    alert(response.data.msg || (isEdit ? '编辑失败' : '新增失败'))
                }
                
            } catch (error) {
                console.error('保存错误:', error)
                alert('操作失败，请稍后重试')
            }
        },
        // ========== 保存商家修改结束 ==========

        // 编辑食品
        editFood(food) {
            console.log('编辑食品:', food)
            this.currentFood = { ...food }
            this.showEditFoodModal = true
        },

        // ========== 修改：删除食品 ==========
        async deleteFood(foodId) {
            if (!confirm('确定要删除这个食品吗？')) {
                return
            }

            try {
                console.log('删除食品:', foodId)
                
                const response = await this.$axios.post('/food/deleteFood', this.$qs.stringify({
                    foodId: foodId
                }))
                
                if (response.data.code === 1) {
                    alert('删除成功！')
                    this.loadFoodList()
                } else {
                    alert(response.data.msg || '删除失败')
                }
                
            } catch (error) {
                console.error('删除错误:', error)
                alert('删除失败，请稍后重试')
            }
        },
        // ========== 删除食品修改结束 ==========

        // ========== 修改：保存食品 ==========
        async saveFood() {
            if (!this.currentFood.foodName.trim()) {
                alert('请输入食品名称')
                return
            }

            try {
                // 设置商家ID
                this.currentFood.businessId = this.selectedBusinessId
                
                const isEdit = this.showEditFoodModal
                console.log(isEdit ? '编辑食品:' : '新增食品:', this.currentFood)
                
                let endpoint
                let params = {
                    foodName: this.currentFood.foodName,
                    foodExplain: this.currentFood.foodExplain,
                    foodPrice: this.currentFood.foodPrice,
                    businessId: this.currentFood.businessId
                }
                
                if (isEdit) {
                    endpoint = '/food/updateFood'
                    params.foodId = this.currentFood.foodId
                } else {
                    endpoint = '/food/addFood'
                }
                
                const response = await this.$axios.post(endpoint, this.$qs.stringify(params))
                
                if (response.data.code === 1) {
                    alert(isEdit ? '编辑成功！' : '新增成功！')
                    this.closeFoodModal()
                    this.loadFoodList()
                } else {
                    alert(response.data.msg || (isEdit ? '编辑失败' : '新增失败'))
                }
                
            } catch (error) {
                console.error('保存错误:', error)
                alert('操作失败，请稍后重试')
            }
        },
        // ========== 保存食品修改结束 ==========

        // 关闭商家模态框
        closeBusinessModal() {
            this.showAddBusinessModal = false
            this.showEditBusinessModal = false
            this.currentBusiness = {
                businessId: null,
                businessName: '',
                businessAddress: '',
                businessExplain: '',
                deliveryPrice: ''
            }
        },

        // 关闭食品模态框
        closeFoodModal() {
            this.showAddFoodModal = false
            this.showEditFoodModal = false
            this.currentFood = {
                foodId: null,
                foodName: '',
                foodExplain: '',
                foodPrice: '',
                businessId: ''
            }
        },

        // 退出登录
        logout() {
            if (confirm('确定要退出登录吗？')) {
                this.$removeSessionStorage('admin')
                this.$router.push('/login')
            }
        }
    }
}
</script>

<style scoped>
    /* 基础样式 */
    .wrapper {
        width: 100%;
        min-height: 100vh;
        background-color: #f5f5f5;
    }

    /* Header */
    header {
        width: 100%;
        height: 12vw;
        background-color: #0097FF;
        color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 4vw;
        box-sizing: border-box;
    }

    .header-left p {
        font-size: 4.5vw;
        font-weight: bold;
    }

    .header-right {
        display: flex;
        align-items: center;
        gap: 3vw;
    }

    .header-right span {
        font-size: 3.2vw;
    }

    .header-right button {
        background-color: rgba(255,255,255,0.2);
        color: #fff;
        border: 1px solid #fff;
        padding: 1.5vw 3vw;
        border-radius: 1vw;
        font-size: 3vw;
        cursor: pointer;
    }

    /* 菜单 */
    .menu-section {
        background-color: #fff;
        padding: 4vw;
        display: flex;
        gap: 4vw;
        border-bottom: 1px solid #eee;
    }

    .menu-item {
        display: flex;
        align-items: center;
        gap: 2vw;
        padding: 2vw 4vw;
        border-radius: 2vw;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 3.5vw;
        color: #666;
    }

    .menu-item:hover,
    .menu-item.active {
        background-color: #0097FF;
        color: #fff;
    }

    /* 内容区 */
    .content {
        padding: 4vw;
    }

    .section-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 4vw;
        flex-wrap: wrap;
        gap: 2vw;
    }

    .section-title h3 {
        font-size: 4.5vw;
        color: #333;
    }

    .business-selector select {
        padding: 2vw;
        border: 1px solid #ddd;
        border-radius: 1vw;
        font-size: 3vw;
    }

    .add-btn {
        background-color: #28a745;
        color: #fff;
        border: none;
        padding: 2vw 3vw;
        border-radius: 1.5vw;
        font-size: 3vw;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 1vw;
    }

    .add-btn:disabled {
        background-color: #ccc;
        cursor: not-allowed;
    }

    /* 列表样式 */
    .business-list,
    .food-list {
        background-color: #fff;
        border-radius: 2vw;
        overflow: hidden;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .list-header,
    .list-item {
        display: grid;
        align-items: center;
        padding: 3vw 2vw;
        border-bottom: 1px solid #eee;
        font-size: 3vw;
    }

    .business-list .list-header,
    .business-list .list-item {
        grid-template-columns: 1fr 3fr 4fr 2fr;
    }

    .food-list .list-header,
    .food-list .list-item {
        grid-template-columns: 1fr 3fr 4fr 1.5fr 2fr;
    }

    .list-header {
        background-color: #f8f9fa;
        font-weight: bold;
        color: #666;
    }

    .list-item:hover {
        background-color: #f9f9f9;
    }

    .col-action {
        display: flex;
        gap: 2vw;
    }

    .edit-btn,
    .delete-btn {
        width: 6vw;
        height: 6vw;
        border: none;
        border-radius: 1vw;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2.5vw;
    }

    .edit-btn {
        background-color: #ffc107;
        color: #fff;
    }

    .delete-btn {
        background-color: #dc3545;
        color: #fff;
    }

    /* 空状态 */
    .empty-state {
        text-align: center;
        padding: 10vw;
        color: #999;
        font-size: 4vw;
    }

    /* 模态框 */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }

    .business-modal {
        width: 90%;
        max-width: 500px;
        background-color: #fff;
        border-radius: 3vw;
        padding: 6vw;
    }

    .business-modal h3 {
        font-size: 4.5vw;
        color: #333;
        margin-bottom: 4vw;
        text-align: center;
    }

    .form-group {
        margin-bottom: 4vw;
    }

    .form-group label {
        display: block;
        font-size: 3.5vw;
        color: #333;
        margin-bottom: 2vw;
    }

    .form-group input,
    .form-group select {
        width: 100%;
        height: 10vw;
        border: 1px solid #ddd;
        border-radius: 1.5vw;
        padding: 0 3vw;
        font-size: 3.5vw;
        box-sizing: border-box;
    }

    .modal-buttons {
        display: flex;
        gap: 3vw;
        margin-top: 6vw;
    }

    .cancel-btn,
    .confirm-btn {
        flex: 1;
        height: 10vw;
        border: none;
        border-radius: 1.5vw;
        font-size: 3.5vw;
        cursor: pointer;
    }

    .cancel-btn {
        background-color: #6c757d;
        color: #fff;
    }

    .confirm-btn {
        background-color: #0097FF;
        color: #fff;
    }
</style>